package common

import (
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/natefinch/lumberjack"
	"github.com/xormplus/xorm"
	"github.com/xormplus/xorm/log"
	"github.com/zw2582/ginlib"
	"go.uber.org/zap"
	"time"
)

type mysqlConfig struct {
	Host     string `json:"host"`
	Port     int    `json:"port"`
	Username string `json:"username"`
	Password string `json:"password"`
	Database string `json:"database"`
	Showlog  bool   `json:"showlog"`
	Chartset string `json:"chartset"`
}

//InitDbFromConsul 初始化xorm数据库
func InitDbFromConsul() *xorm.Engine {
	if microConsulConfig == nil {
		panic("请先初始化Consul配置中心")
	}
	mc := mysqlConfig{}
	if err := microConsulConfig.Get("mysql").Scan(&mc); err != nil {
		panic(err)
	}

	//使用xorm连接配置
	if mc.Port == 0 {
		mc.Port = 6379
	}
	if mc.Chartset == "" {
		mc.Chartset = "utf8mb4"
	}
	connDns := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=%s", mc.Username, mc.Password, mc.Host, mc.Port, mc.Database, mc.Chartset)

	fmt.Println("连接mysql:", connDns)
	eng, err := xorm.NewEngine("mysql", connDns)
	if err != nil {
		panic(err)
	}
	eng.SetTZLocation(time.Local)

	//设置日志
	hook := lumberjack.Logger{
		Filename:   "./logs/sql.log", //日志文件路径
		MaxSize:    128,              //最大字节
		MaxAge:     30,
		MaxBackups: 7,
		Compress:   true,
	}
	logger := log.NewSimpleLogger(&hook)

	//设置日志等级
	eng.SetLogger(logger)
	eng.SetLogLevel(log.LOG_DEBUG)
	eng.ShowSQL(mc.Showlog)
	if err := eng.Ping(); err != nil {
		panic(err)
	}

	//检测配置是否显示sql日志
	w, err := microConsulConfig.Watch("mysql")
	if err != nil {
		panic(err)
	}
	go func() {
		for {
			if d, err := w.Next(); err != nil {
				break
			} else {
				tmp := mysqlConfig{}
				if err := d.Scan(&tmp); err != nil {
					continue
				} else {
					if tmp.Showlog != mc.Showlog {
						mc.Showlog = tmp.Showlog
						//更改xorm引擎配置
						ginlib.Logger.Info("更改sql语句打印行为", zap.Bool("showlog", mc.Showlog))
						eng.ShowSQL(mc.Showlog)
					}
				}
			}
		}
	}()

	return eng
}
